package org.example.managere.service.feibiao.impl;

import lombok.RequiredArgsConstructor;
import org.example.managere.dto.feibiao.AmArchivesDegradationDto;
import org.example.managere.entity.feibiao.AmArchivesBase;
import org.example.managere.entity.feibiao.AmArchivesDegradation;
import org.example.managere.repository.feibiao.AmArchivesBaseRepository;
import org.example.managere.repository.feibiao.AmArchivesDegradationRepository;
import org.example.managere.service.feibiao.AmArchivesDegradationService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 电机性能退化监测服务实现类
 */
@Service
@RequiredArgsConstructor
public class AmArchivesDegradationServiceImpl implements AmArchivesDegradationService {

    private final AmArchivesDegradationRepository degradationRepository;
    private final AmArchivesBaseRepository baseRepository;

    /**
     * 将实体转换为DTO
     */
    private AmArchivesDegradationDto convertToDto(AmArchivesDegradation degradation) {
        try {
            AmArchivesDegradationDto dto = new AmArchivesDegradationDto();
            dto.setDegradationId(degradation.getDegradationId());
            
            // 处理电机基本信息
            AmArchivesBase motorBase = degradation.getMotorId();
            if (motorBase != null) {
                dto.setMotorId(motorBase.getMotorId());
                dto.setMotorType(motorBase.getMotorType());
                dto.setManufacturer(motorBase.getManufacturer());
            } else {
                dto.setMotorId("未设置");
                dto.setMotorType("无");
                dto.setManufacturer("无");
            }
            
            dto.setMeasurementTime(degradation.getMeasurementTime());
            dto.setEfficiencyDegradation(degradation.getEfficiencyDegradation());
            dto.setPowerDegradation(degradation.getPowerDegradation());
            dto.setRemainingLifePrediction(degradation.getRemainingLifePrediction());
            
            return dto;
        } catch (Exception e) {
            System.err.println("转换退化记录DTO时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("转换退化记录失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 将DTO转换为实体
     */
    private AmArchivesDegradation convertToEntity(AmArchivesDegradationDto dto) {
        AmArchivesDegradation entity = new AmArchivesDegradation();
        
        if (dto.getDegradationId() != null) {
            entity.setDegradationId(dto.getDegradationId());
        }
        
        // 查找关联的电机基本信息
        AmArchivesBase motorBase = baseRepository.findById(dto.getMotorId())
                .orElseThrow(() -> new IllegalArgumentException("电机ID不存在: " + dto.getMotorId()));
        
        entity.setMotorId(motorBase);
        entity.setMeasurementTime(dto.getMeasurementTime());
        entity.setEfficiencyDegradation(dto.getEfficiencyDegradation());
        entity.setPowerDegradation(dto.getPowerDegradation());
        entity.setRemainingLifePrediction(dto.getRemainingLifePrediction());
        
        return entity;
    }

    @Override
    @Transactional
    public AmArchivesDegradationDto save(AmArchivesDegradationDto amArchivesDegradationDto) {
        AmArchivesDegradation entity = convertToEntity(amArchivesDegradationDto);
        AmArchivesDegradation savedEntity = degradationRepository.save(entity);
        return convertToDto(savedEntity);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<AmArchivesDegradationDto> findById(Integer degradationId) {
        // 直接使用原始方法查询数据，但确保在事务内处理关联对象
        Optional<AmArchivesDegradation> degradationOpt = degradationRepository.findById(degradationId);
        degradationOpt.ifPresent(this::initializeMotorBase);
        return degradationOpt.map(this::convertToDto);
    }

    @Override
    @Transactional
    public AmArchivesDegradationDto update(AmArchivesDegradationDto amArchivesDegradationDto) {
        // 确保记录存在
        if (amArchivesDegradationDto.getDegradationId() == null || 
                !degradationRepository.existsById(amArchivesDegradationDto.getDegradationId())) {
            throw new IllegalArgumentException("无法更新不存在的记录，ID: " + amArchivesDegradationDto.getDegradationId());
        }
        
        AmArchivesDegradation entity = convertToEntity(amArchivesDegradationDto);
        AmArchivesDegradation updatedEntity = degradationRepository.save(entity);
        return convertToDto(updatedEntity);
    }

    @Override
    @Transactional
    public void deleteById(Integer degradationId) {
        degradationRepository.deleteById(degradationId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesDegradationDto> findAll() {
        List<AmArchivesDegradation> degradations = degradationRepository.findAll();
        initializeMotorBaseCollection(degradations);
        return degradations.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public Page<AmArchivesDegradationDto> findAll(String motorId, Pageable pageable) {
        return degradationRepository.findAllDtoByMotorId(motorId, pageable);
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesDegradationDto> findByMotorId(String motorId) {
        List<AmArchivesDegradation> degradations = degradationRepository.findByMotorId_MotorId(motorId);
        initializeMotorBaseCollection(degradations);
        return degradations.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    /**
     * 在事务内初始化关联对象
     */
    private void initializeMotorBase(AmArchivesDegradation degradation) {
        if (degradation != null && degradation.getMotorId() != null) {
            // 强制初始化 - 在事务内访问属性触发加载
            try {
                System.out.println("正在初始化电机对象, 记录ID: " + degradation.getDegradationId());
                AmArchivesBase motorBase = degradation.getMotorId();
                String motorId = motorBase.getMotorId();
                String motorType = motorBase.getMotorType();
                String manufacturer = motorBase.getManufacturer();
                System.out.println("成功初始化电机对象, 电机ID: " + motorId + ", 型号: " + motorType + ", 厂商: " + manufacturer);
            } catch (Exception e) {
                System.err.println("初始化关联对象失败: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("电机对象为null，无需初始化, 记录ID: " + (degradation != null ? degradation.getDegradationId() : "null"));
        }
    }
    
    /**
     * 在事务内初始化关联对象集合
     */
    private void initializeMotorBaseCollection(List<AmArchivesDegradation> degradations) {
        if (degradations != null) {
            degradations.forEach(this::initializeMotorBase);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesDegradationDto> findByMeasurementTimeBetween(Date startTime, Date endTime) {
        List<AmArchivesDegradation> degradations = degradationRepository.findByMeasurementTimeBetween(startTime, endTime);
        initializeMotorBaseCollection(degradations);
        return degradations.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<AmArchivesDegradationDto> findByMotorIdAndTimeRange(String motorId, Date startTime, Date endTime) {
        List<AmArchivesDegradation> degradations = degradationRepository.findByMotorIdAndTimeRange(motorId, startTime, endTime);
        initializeMotorBaseCollection(degradations);
        return degradations.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }
} 